package server.servlet;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.container.Context;
import server.container.Wrapper;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * @description:
 * @author: Archie Wan
 * @time: 2020/12/28 14:04
 */
public class ContextLoader {
    
    // 默认 Servlet 的 web.xml 配置都放在 /WEB-INF/web.xml
    private static final String WEB = "/webapp/WEB-INF/web.xml";
    
    private Context context;
    private String contextPath;
    private ClassLoader classLoader;
    
    public ContextLoader(Context context) {
        this.context = context;
        this.contextPath = context.getContextPath();
        this.classLoader = context.getClassLoader();
    }
    
    public void load() {
    
        try {
            FileInputStream inputStream = new FileInputStream(contextPath + WEB);
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();
    
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (Element element : selectNodes) {
                Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletNameElement.getStringValue();
        
                Element servletClassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletClassElement.getStringValue();
        
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
        
                Wrapper wrapper = new Wrapper();
                wrapper.setUrlPattern(urlPattern);
                wrapper.setServlet((Servlet) classLoader.loadClass(servletClass).newInstance());
                wrapper.setClassLoader(classLoader);
                context.addWrapper(wrapper);
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    
    }

}
